import { getIntroduceHome, getIntroduceDetail } from '@/api/introduce.js'
export default {
  namespaced: true,
  state: ()=>({
    // 介绍页导航
    introduceNav: [],
    // 导航详情
    introduceDetail: {},
    currentId: ''
  }),
  mutations: {
    // 设置导航
    setIntroduceNav(state, data) {
      state.introduceNav = data
    },
    // 设置导航详情
    setIntroduceDetail(state, data) {
      state.introduceDetail = data
    },
    // 设置当前页路由
    setRoute(state, data) {
      state.nav_route = '/' + data
    },
    // 设置当前id
    setCurrentId(state, data) {
      state.currentId = data
    }
  },
  actions: {
    // 页面初始化
    async init({ dispatch, commit, state }, params) {
      // 一斜杠结尾，且不只是斜杠
      params.route_path = params.route_path.length>1&&params.route_path.slice(-1)==='/'?params.route_path.slice(0,-1):params.route_path
      commit('setRoute', params.route_path)
      let res = await dispatch('getIntroduceNav', params)
      // 去掉路由后面的/再做判断；
      let arr = res.filter(item => item.nav_route === state.nav_route)
      let id = ''
      if (arr && arr.length) {
        id = arr[0].id
      }
      let detailParams = { id }
      commit('setCurrentId', id)
      await dispatch('getIntroduceDetail', detailParams)
    },
    // 获取导航
    async getIntroduceNav({ commit }, params) {
      let res = await getIntroduceHome(params).catch(err => {
        return {
          data: {}
        }
      })
      if (res.errcode === 0 && res.data && res.data.children && res.data.children.length) {
        res.data.children.forEach(item=>{
          if(item.nav_route.slice(-1)==='/'&&params.route_path.length>1){
            item.nav_route = item.nav_route.slice(0,-1)
          }else{
            item.nav_route = item.nav_route
          }
        })
        commit('setIntroduceNav', res.data.children)
        return res.data.children
      } else {
        commit('setIntroduceNav', [])
        return []
      }
    },
    // 获取导航详情
    async getIntroduceDetail({ commit }, params) {
      let res = await getIntroduceDetail(params).catch(err => {
        return {
          data: {}
        }
      })
      if (+res.errcode === 0 && res.data) {
        commit('setIntroduceDetail', res.data)
      } else {
        commit('setIntroduceDetail', {})
      }
    }
  }
}
